<template>
  <view class="course-page">
    <!-- 导航栏组件 -->
    <NavBar :click="handleGoHome"></NavBar>
    <view class="content" :style="getContentStyle()">
      <image class="result-icon" :src="percentageType === 'file' ? '/static/images/result_1.png' : '/static/images/result_2.png'" mode="scaleToFill"></image>
      <text class="result-title">{{getResultTitle}}</text>
      <view v-if="percentageType !== 'error'" class="progress-bar">
        <view class="progress-line" :style="progressStyle"></view>
      </view>
      <text v-if="percentageType !== 'file'"  class="result-hint">可在 [我的 - 学习记录] 中查阅</text>
      <view v-if="isFail" @click="handleCommit" class="goBack-btn"><text>重新提交</text></view>
      <view v-if="percentageType === 'error'" @click="handleReset" class="goBack-btn"><text>重新录制</text></view>
      
    </view>
  </view>
</template>

<script >
import { saveExercise } from '@/api/course.js'
import { uploadFile } from '@/api/upload.js'
import { getReportState, getLesson } from '@/api/course.js'
export default {
  data() {
    return {
      isFail: false,
      progress: 0,
      progressInterval: null,
      pageInfo: {},
      percentageType: 'file', // 进度条步长 file: 文件, report: 报告, error: 报告出错
      isStopRequest: false, // 是否停止循环请求
      questionsMap: {
        F: '这个产品有什么特征？',
        A: '相对竞争对手有什么优势？',
        B: '这些优势能给客户带来什么好处？',
        E: '有什么证据支撑？如数据、案例、认证等',
      },
      questionsTagMap: {
        F: '特征',
        A: '优势',
        B: '利益',
        E: '证据',
      },
    }
  },
  computed: {
    progressStyle() {
      return {
        width: this.progress + '%'
      }
    },
    getResultTitle() {
      if (this.percentageType === 'file') {
        return '正在上传视频...'
      } else if (this.percentageType === 'report') {
        return '视频上传成功，AI分析中...'
      } else {
        return '好像没捕捉到您的面部或声音，请确保光线充足、环境安静，并重新录制。'
      }
    }
  },
  onLoad(options) {
    this.pageInfo = JSON.parse(options.l)
    this.handleCommit()
    uni.setKeepScreenOn({
      keepScreenOn: true
    });
  },
  onHide() {
    this.isStopRequest = true
    uni.setKeepScreenOn({
      keepScreenOn: false
    });
    if (this.progressInterval) {
      clearInterval(this.progressInterval)
      this.progressInterval = null
    }
  },
  methods: {
    getContentStyle() {
      const statusBarHeight = uni.getSystemInfoSync().statusBarHeight || 0
      return {
        height: `calc(100% - ${(statusBarHeight + 44)}px)`
      }
    },
    handleGoHome() {
      uni.showModal({
        title: '提示',
        content: '是否确认放弃提交？',
        success: (res) => {
          this.isStopRequest = true
          if (res.confirm) {
            uni.redirectTo({
              url: `/pages/course/info/index?courseId=${this.pageInfo.courseId}&lessonId=${this.pageInfo.lessonId}`
            })
          }
        }
      });
    },
    async handleReset() {
      try {
        const info= await getLesson(this.pageInfo.courseId, this.pageInfo.lessonId)
        let questions = []
        Object.keys(this.questionsMap).map((key) => {
          if (info.salesLanguageMap[key]) {
            questions.push({
              key,
              question: this.questionsMap[key],
              tag: this.questionsTagMap[key],
              response: info.salesLanguageMap[key]
            })
          }
        })
        const pageData = {
          questions: questions,
          courseId: this.pageInfo.courseId,
          lessonId: this.pageInfo.lessonId,
        }
        const json = JSON.stringify(pageData)
        uni.redirectTo({
          url: `/pages/course/follow/index?l=${json}`
        })
      } catch(e) {
        console.log(e)
      }
    },
    async handleCommit() {
      this.percentageType = 'file'
      this.progress = 1
      this.isFail = false
      try {
        // 上传视频
        const videoRes = await uploadFile({filePath: this.pageInfo.videoUrl, onProgress: (res) => {
          this.progress = res.progress
        }})
        console.log('视频上传成功')
        // 上传封面图片
        // const oldVideoProgress = this.progress
        // const videoPosterRes = await uploadFile({filePath: this.pageInfo.videoPoster, onProgress: (res) => {
        //   this.progress = oldVideoProgress + res.progress * 0.33
        // }})
        // videoPosterRes[0].isPicture = 1
        // console.log('封面上传成功')
        // 上传音频文件
        // const oldvoiceProgress = this.progress
        // const voicePathRes = await uploadFile({filePath: this.pageInfo.voicePath, onProgress: (res) => {
        //   this.progress = oldvoiceProgress + res.progress * 0.33
        // }})
        // console.log('音频上传成功')
        const info = uni.getSystemInfoSync()

        const parmas = {
          files: [videoRes[0], this.pageInfo.videoPoster[0]],
          lessonId: this.pageInfo.lessonId,
          courseId: this.pageInfo.courseId,
          exerciseType: this.pageInfo.exerciseType,
          useTime: this.pageInfo.useTime,
          platformInfo: {
            platform: info.platform,
            system: info.system,
            model: info.model,
            uniPlatform: info.uniPlatform,
            osName: info.osName,
            osVersion: info.osVersion,
            deviceBrand: info.deviceBrand,
            deviceModel: info.deviceModel
          }
        }
        console.log('parmas--', JSON.stringify(parmas))
        const exerciseId = await saveExercise(parmas)
        console.log('exerciseId--', exerciseId)
        this.percentageType = 'report'
        this.progress = 0
        this.isStopRequest = false
        
        const pollReport = async () => {
          if (this.isStopRequest) {
            return
          }
          if (this.progress === 0) {
            this.progressInterval = setInterval(() => {
              this.progress += 1
              if (this.progress >= 95) {
                this.progress = 95
                clearInterval(this.progressInterval)
                this.progressInterval = null
              }
            }, 1000)
          }
          const reportData = await getReportState(exerciseId)
          console.log('获取报告进度结果', reportData)
          if (Number(reportData) === 2) {
          // if (reportData.exerciseId) {
            this.progress = 100
            this.isStopRequest = true
            clearInterval(this.progressInterval)
            this.progressInterval = null
            return reportData
          } else if (Number(reportData) === 3) {
            this.percentageType = 'error'
            this.isStopRequest = true
            clearInterval(this.progressInterval)
            this.progressInterval = null
            return 'error'
          }
          
          // 添加延迟避免频繁请求
          await new Promise(resolve => setTimeout(resolve, 3000))
          return pollReport()
        }
        const result = await pollReport()
        if (result === 'error') {
          return
        }
        uni.redirectTo({url: `/pages/course/follow/report/index?exerciseId=${exerciseId}`})
      } catch(err) {
        this.isFail = true
        uni.showToast({
          title: err.message || '提交失败',
          icon: 'none',
          duration: 2000
        });
      }
    },
  }
}
</script>

<style lang="scss">
.course-page {
  width: 100%;
  height: 100vh;
  background: linear-gradient(207deg, #DCECFF 2%, #F6F7FB 61%);
}

.content {
  width: 100%;
  padding: 32rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  .result-icon{
    width: 290rpx;
    height: 296rpx;
    margin-top: 200rpx;
  }
  .result-title{
    font-size: 32rpx;
    font-weight: 600;
    line-height: 48rpx;
    text-align: center;
    color: #333333;
    margin-top: 32rpx;
  }
  .result-hint{
    font-size: 28rpx;
    line-height: 48rpx;
    text-align: center;
    color: #666666;
    margin-top: 16rpx;
  }
}
.goBack-btn{
  width: 328rpx;
  height: 96rpx;
  border-radius: 24rpx;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  background: #FFFFFF;
  margin-top: 64rpx;
  text{
    font-size: 32rpx;
    font-weight: 600;
    line-height: 48rpx;
    color: #666666;
  }
}
.progress-bar{
  width: 526rpx;
  height: 8rpx;
  border-radius: 999px;
  background: #E2E5E8;
  position: relative;
  margin-top: 16rpx;
  margin-bottom: 48rpx;
  .progress-line{
    height: 8rpx;
    border-radius: 999px;
    background: #155BD4;
    position: absolute;
    top: 0;
    left: 0;
  }
}
</style>
